package com.linefly.online_car.Custom;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.services.core.LatLonPoint;
import com.linefly.online_car.R;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import Been.been_event;
import Util.GaodeToGPS;
import Util.JsonUtil;
import Util.NavigationBarUtil;
import Util.ToastUtil;
import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * Created by liheng on 2018/11/16.
 */

public class Custom_Dialog_zhalan extends AppCompatActivity {

    private Context context;
    EditText et_mingcheng;
    String mingcheng,str_json;
    private TextView tv_sousuo;

    private static final int LOCATION_CODE = 1;
    private LocationManager lm;//【位置管理】
    ///////////////////////////////////地图相关//////////////////////////
    MapView mMapView = null;
    AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private MarkerOptions markerOption;

    private ArrayList arrayList_point = new ArrayList();
    private List<LatLng> latlngs = new ArrayList<LatLng>();
    private Polygon polygon;

    private int f_click = 0;
    String type = "";




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_dialog_zhalan);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }


        if (NavigationBarUtil.hasNavigationBar(this)) {
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }

        tv_sousuo = (TextView)findViewById(R.id.sousuo);
        et_mingcheng = (EditText)findViewById(R.id.mingcheng);


        tv_sousuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(arrayList_point.size() < 3 || et_mingcheng.getText().toString().length() == 0){
                    ToastUtil.toast(Custom_Dialog_zhalan.this,"请完善电子围栏或者名称信息");
                }else {
                    String str = JsonUtil.jsonEnclose(arrayList_point).toString();
                    Log.e("数组打包", str);
                    EventBus.getDefault().post(new been_event(type, et_mingcheng.getText().toString(), str));
                    finish();
                }


            }
        });

        Intent intent = getIntent();

        et_mingcheng.setText(intent.getStringExtra("name"));
        String json = intent.getStringExtra("json");
        type = intent.getStringExtra("type");
        if(json.length()>0) {
            arrayList_point = (ArrayList) JsonUtil.jsonParse(json);
        }



        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);


        if (aMap == null) {
            aMap = mMapView.getMap();


        }
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setCompassEnabled(false);
        mUiSettings.setScaleControlsEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setTiltGesturesEnabled(false);


        ///////////////地图缩放事件的监听//////
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (cameraPosition.zoom <= 9) {
                    //Toast.makeText(MainActivity.this,String.valueOf(cameraPosition.zoom),Toast.LENGTH_LONG).show();
                }
            }
        });


        //地图的点击事件
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(final LatLng latLng) {
                Log.e("ditu", "onMapClick: ");
                if(f_click == 1){
                    f_click = 0;
                }else {

                    new SweetAlertDialog(Custom_Dialog_zhalan.this)
                            .setTitleText("确定添加点?")
                            .setContentText("(" + String.valueOf(latLng.latitude) + "," + String.valueOf(latLng.longitude) + ")")
                            .setConfirmText("确定")
                            .setCancelText("取消")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismissWithAnimation();
                                    add_Point(latLng);

                                }
                            })
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                }



            }
        });
        //标记点点击事件
        AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

//

                f_click = 1;

                return false;
            }
        };
        aMap.setOnMarkerClickListener(markerClickListener);

        AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {

                remove_Point(arg0);//删除是1

            }
        };
//Marker的信息窗点击事件
        aMap.setOnInfoWindowClickListener(listener);


        set_Map();//把原先有的点和图像放入地图；

    }

    public void set_Map(){



        for(int i = 0;i<arrayList_point.size();i++){
            HashMap hashMap1 = (HashMap)arrayList_point.get(i);

            LatLng latLng = new LatLng(Double.valueOf(hashMap1.get("lat").toString()),Double.valueOf(hashMap1.get("lng").toString()));
            markerOption = new MarkerOptions();
            CoordinateConverter converter = new CoordinateConverter(Custom_Dialog_zhalan.this);
// CoordType.GPS 待转换坐标类型
            converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 LatLng类型
            converter.coord(latLng);
// 执行转换操作
            LatLng desLatLng = converter.convert();
            markerOption.position(desLatLng);
            markerOption.draggable(false);//设置Marker可拖动
            markerOption.setFlat(true);//设置marker平贴地图效果
            //markerOption.anchor(0.5f, 0.5f);
            Marker marker = aMap.addMarker(markerOption);
            marker.setTitle("点击删除");
            marker.showInfoWindow();

            latlngs.add(desLatLng);


        }

        polygon = aMap.addPolygon(new PolygonOptions().addAll(latlngs).fillColor(Color.argb(20, 0, 0, 255)).
                strokeColor(Color.argb(0, 0, 0, 255)).
                strokeWidth(0));

        //做个延时
        if(latlngs.size()>0){
            get_Dingwei(latlngs.get(0));

        }






    }
    public void get_Dingwei(final LatLng latLng){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 2000);//3秒后执行TimeTask的run方法

    }

    public void remove_Point(Marker marker){
        //更新地图的点和对应的列表


            //删除
            for(int i = 0;i<latlngs.size();i++){

                if(marker.getPosition().latitude == latlngs.get(i).latitude
                        && marker.getPosition().longitude == latlngs.get(i).longitude){
                    arrayList_point.remove(i);
                    latlngs.remove(i);

                    break;
                }


            }

            marker.remove();
            polygon.remove();
            polygon = aMap.addPolygon(new PolygonOptions().addAll(latlngs).fillColor(Color.argb(20, 0, 0, 255)).
                    strokeColor(Color.argb(0, 0, 0, 255)).
                    strokeWidth(0));








    }

    public void add_Point(LatLng latLng){
        //传到原始数据数组把经纬度进行处理

        LatLonPoint latLonPoint = GaodeToGPS.toGPSPoint(latLng.latitude,latLng.longitude);
        HashMap hashMap = new HashMap();
        hashMap.put("lat",String.valueOf(latLonPoint.getLatitude()));
        hashMap.put("lng",String.valueOf(latLonPoint.getLongitude()));
        hashMap.put("name","无");
        arrayList_point.add(hashMap);

        markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.setFlat(true);//设置marker平贴地图效果
        //markerOption.anchor(0.5f, 0.5f);
        Marker marker = aMap.addMarker(markerOption);
        marker.setTitle("点击删除");
        marker.showInfoWindow();

        latlngs.add(latLng);

        polygon.remove();
        polygon = aMap.addPolygon(new PolygonOptions().addAll(latlngs).fillColor(Color.argb(20, 0, 0, 255)).
                strokeColor(Color.argb(0, 0, 0, 255)).
                strokeWidth(0));





    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();


        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    public void click_back(View view){
        finish();
    }



}

